using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Win32;

namespace TmxLib
{
    public abstract class NsiExecBase
    {
        public abstract void Exec(string nsiProject);

        public static NsiExecBase GetInstance()
        {
            return new NsiExecPreinstalled();
        }
    }

    public class NsiExecPreinstalled: NsiExecBase
    {
        public override void Exec(string nsiProject)
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.Arguments = "\"" + nsiProject + "\"";
            psi.FileName = GetNsisExecutable();
            psi.UseShellExecute = false;
            using(Process p = Process.Start(psi))
            {
                p.WaitForExit();
                if (p.ExitCode != 0)
                {
                    throw new Exception("NSIS failed with exit code " + p.ExitCode);
                }
            }
        }

        private static string GetNsisExecutable()
        {
            const string keyPath = @"SOFTWARE\NSIS";
            using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(keyPath))
            {
                if (rk != null)
                {
                    string path = rk.GetValue(string.Empty) as string;
                    if (path != null && path.Length > 0)
                    {
                        string exe = Path.Combine(path, "makensis.exe");
                        if (File.Exists(exe))
                            return exe;

                    }
                }
            }

            throw new Exception("NSIS is not found");
        }
    }

}
